// 模拟后端服务
import { ref } from 'vue';

// 模拟数据库 - 从localStorage获取用户数据，如果没有则使用默认数据
const getUsers = () => {
  const storedUsers = localStorage.getItem('mockUsers');
  return storedUsers ? JSON.parse(storedUsers) : [
    { id: 1, username: 'admin', password: '123456', nickname: '管理员' }
  ];
};

// 初始化用户数据
const users = ref(getUsers());

// 保存用户数据到localStorage
const saveUsers = () => {
  localStorage.setItem('mockUsers', JSON.stringify(users.value));
};

// 模拟延迟
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

// 模拟注册接口
export const register = async (userData) => {
  await delay(500); // 模拟网络延迟
  
  // 检查用户名是否已存在
  const existUser = users.value.find(user => user.username === userData.username);
  if (existUser) {
    return {
      code: 400,
      message: '用户名已存在',
      data: null
    };
  }
  
  // 创建新用户
  const newUser = {
    id: users.value.length + 1,
    username: userData.username,
    password: userData.password,
    nickname: userData.nickname || userData.username
  };
  
  users.value.push(newUser);
  
  // 保存到localStorage
  saveUsers();
  
  return {
    code: 200,
    message: '注册成功',
    data: {
      id: newUser.id,
      username: newUser.username,
      nickname: newUser.nickname
    }
  };
};

// 模拟登录接口
export const login = async (loginData) => {
  await delay(500); // 模拟网络延迟
  
  // 查找用户
  const user = users.value.find(
    user => user.username === loginData.username && user.password === loginData.password
  );
  
  if (!user) {
    return {
      code: 401,
      message: '用户名或密码错误',
      data: null
    };
  }
  
  // 生成模拟token
  const token = `mock_token_${user.id}_${Date.now()}`;
  
  return {
    code: 200,
    message: '登录成功',
    data: {
      token,
      userInfo: {
        id: user.id,
        username: user.username,
        nickname: user.nickname
      }
    }
  };
};

// 模拟获取用户信息接口
export const getUserInfo = async () => {
  await delay(300); // 模拟网络延迟
  
  // 从localStorage获取token
  const token = localStorage.getItem('token');
  if (!token) {
    return {
      code: 401,
      message: '未登录或登录已过期',
      data: null
    };
  }
  
  // 解析token获取用户ID
  const tokenParts = token.split('_');
  if (tokenParts.length < 2) {
    return {
      code: 401,
      message: '无效的token',
      data: null
    };
  }
  
  const userId = parseInt(tokenParts[1]);
  
  // 查找对应用户
  const user = users.value.find(u => u.id === userId);
  if (!user) {
    return {
      code: 401,
      message: '用户不存在',
      data: null
    };
  }
  
  return {
    code: 200,
    message: '获取成功',
    data: {
      id: user.id,
      username: user.username,
      nickname: user.nickname
    }
  };
};